package com.amigo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amigo.helper.Constants;
import com.amigo.helper.JsonFileUtility;
import com.amigo.helper.ServiceHandler;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;

public class Login extends FragmentActivity implements ConnectionCallbacks,
		OnConnectionFailedListener {

	private static String url = Constants.getBaseUrl() + "login";
	
	private EditText user_input;
	private EditText password_input;
	private ImageView logo;
	
	private TextView loading;
	private String Token;
	private String DB_USER;
	boolean Success;
	private String Message, username, password;
	
	
	private String FBuser_id, FBuser_name, FBuser_email, FBuser_gender;
	private String url_Fb = Constants.base_url + "checkFacebookUser";

	private String GPlus_id, GPlus_name, GPlus_email;
	private int GPlus_gender;
	private String url_gplus = Constants.base_url + "checkGoogleUser";
	private String checkgpluslogout;
	
	private Button SignUp ;
	

	/* Request code used to invoke sign in user interactions. */
	private static final int RC_SIGN_IN = 0;

	/* Client used to interact with Google APIs. */
	private GoogleApiClient mGoogleApiClient;

	/*
	 * A flag indicating that a PendingIntent is in progress and prevents us
	 * from starting further intents.
	 */
	private boolean mIntentInProgress;
	private boolean mSignInClicked;

	/*
	 * Store the connection result from onConnectionFailed callbacks so that we
	 * can resolve them when the user clicks sign-in.
	 */
	private ConnectionResult mConnectionResult;
	private Session.StatusCallback statusCallback = new SessionStatusCallback();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login);

		
		mGoogleApiClient = new GoogleApiClient.Builder(this)
				.addConnectionCallbacks(this)
				.addOnConnectionFailedListener(this).addApi(Plus.API)
				.addScope(Plus.SCOPE_PLUS_LOGIN).build();
		
		
		SignInButton Gplus = (SignInButton) findViewById(R.id.sign_in_button);
		Gplus.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (internetconnected()){
				if (v.getId() == R.id.sign_in_button
						&& !mGoogleApiClient.isConnecting()) {
					mSignInClicked = true;
					mGoogleApiClient.connect();
				}
			}
			else{
				startActivity(new Intent (Login.this , MainActivity.class));
			}

			}
		});

		user_input = (EditText) findViewById(R.id.username);
		password_input = (EditText) findViewById(R.id.password);
		logo = (ImageView) findViewById(R.id.logo);
		loading = (TextView) findViewById(R.id.loading);
		loading.setVisibility(View.INVISIBLE);
		Button login = (Button) findViewById(R.id.login);
		login.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				user_input.setEnabled(false);
				password_input.setEnabled(false);
				user_input.setError(null);
				username = user_input.getText().toString();
				password = password_input.getText().toString();
				if (username.isEmpty()) {
					user_input.setError("Username Cannot be Left Blank");
					user_input.setEnabled(true);
					password_input.setEnabled(true);
				}
				if (password.isEmpty()) {
					password_input.setError("Password Cannot be Left Blank");
					user_input.setEnabled(true);
					password_input.setEnabled(true);
				} else
					new LoginTask().execute();

			}
		});
SignUp = (Button) findViewById(R.id.Signup);
SignUp.setOnClickListener(new View.OnClickListener() {
	
	@Override
	public void onClick(View v) {
		
		startActivity(new Intent(Login.this , SignUp.class));
		finish();
		
	}
});
		// FaceBook Login Code

		// start Facebook Login
		LoginButton authButton = (LoginButton) findViewById(R.id.authButton);
		authButton.setReadPermissions(Arrays.asList("public_profile", "email"));
		authButton.setSessionStatusCallback(statusCallback);
		authButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
				logo.startAnimation(AnimationUtils.loadAnimation(Login.this,
						R.anim.progress_animation));
				loading.setVisibility(View.VISIBLE);
				
			}
		});

		if (Session.getActiveSession() != null
				&& Session.getActiveSession().isOpened())

		{
			Session.getActiveSession().close();
			Session.getActiveSession().closeAndClearTokenInformation();
		}
		

		checkgpluslogout = JsonFileUtility.ReadJsonData("Logout_GPLUS");
		
	}

	
	protected void onStart() {
		super.onStart();
		
		if (checkgpluslogout.equals("true"))
		{
		
			mGoogleApiClient.disconnect();
			
		}
		else if (checkgpluslogout.equals("false")){
		mGoogleApiClient.connect();
		}
		}
	
	
	private class SessionStatusCallback implements Session.StatusCallback {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			if (session.isOpened()) {

				// make request to the /me API
				Request.newMeRequest(session, new Request.GraphUserCallback() {

					// callback after Graph API response with user object
					@Override
					public void onCompleted(GraphUser user, Response response) {
						if (user != null) {
							FBuser_id = user.getId();
							FBuser_name = user.getName();

							try {
								FBuser_email = user.getInnerJSONObject()
										.getString("email");
								FBuser_gender = user.getInnerJSONObject()
										.getString("gender");
							} catch (JSONException e) {

								e.printStackTrace();
							}

							new CheckFaceBookUserTask().execute();
						}
					}
				}).executeAsync();
			}
		}
	}
	
	
	

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode != RC_SIGN_IN) {
			Session.getActiveSession().onActivityResult(this, requestCode,
					resultCode, data);
		}
		if (requestCode == RC_SIGN_IN) {
			if (resultCode != RESULT_OK) {
				mSignInClicked = false;
			}

			mIntentInProgress = false;

			if (!mGoogleApiClient.isConnecting()) {
				mGoogleApiClient.connect();
			}
		}
	}

	private class LoginTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			logo.startAnimation(AnimationUtils.loadAnimation(Login.this,
					R.anim.progress_animation));
			loading.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// Creating service handler class instance
			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("username", username));
			params.add(new BasicNameValuePair("password", password));
			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST,
					params);

			Log.d("Response: ", "> " + jsonStr);

			if (jsonStr != null) {
				try {

					JSONObject jsonObj = new JSONObject(jsonStr);

					Success = jsonObj.getBoolean("success");
					Message = jsonObj.getString("message");
					Token = jsonObj.getString("token");

					if (Success == true) {
						JSONObject user = jsonObj.getJSONObject("user");
						DB_USER = user.toString();

					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			user_input.setEnabled(true);
			password_input.setEnabled(true);
			logo.clearAnimation();
			loading.setVisibility(View.INVISIBLE);
			if (Success == false) {
				if (Message.contains("User")) {
					user_input.setError(Message);
					user_input.requestFocus();
				} else if (Message.contains("Password")) {
					user_input.setError(Message);
					password_input.setError("Wrong Username or Password");
				}
			}

			if (Success == true) {

				JsonFileUtility
						.CreateAndSaveFile(Constants.TAG_UserGUID, Token);
				JsonFileUtility.CreateAndSaveFile(Constants.TAG_UserObject,
						DB_USER);
				Intent i = new Intent(Login.this, Dashboard.class);

				startActivity(i);

			}

		}

	}

	private class CheckFaceBookUserTask extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			logo.startAnimation(AnimationUtils.loadAnimation(Login.this,
					R.anim.progress_animation));
			loading.setVisibility(View.VISIBLE);
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> params_fb = new ArrayList<NameValuePair>();
			params_fb.add(new BasicNameValuePair("fb_id", FBuser_id));
			params_fb
					.add(new BasicNameValuePair("pass", Constants.Password_FB));
			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url_Fb, ServiceHandler.POST,
					params_fb);

			Log.d("Response: ", "> " + jsonStr);

			if (jsonStr != null) {
				try {

					JSONObject jsonObj = new JSONObject(jsonStr);

					Success = jsonObj.getBoolean("success");
					Message = jsonObj.getString("message");

					if (Success == true) {
						Token = jsonObj.getString("token");
						JSONObject user = jsonObj.getJSONObject("user");
						DB_USER = user.toString();

					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			user_input.setEnabled(true);
			password_input.setEnabled(true);
			logo.clearAnimation();
			loading.setVisibility(View.INVISIBLE);
			if (Success == false && !FBuser_id.isEmpty()) {
				Intent i = new Intent(Login.this, SignUp.class);
				i.putExtra("FB_USER_exists", true);
				i.putExtra("FBuser_id", FBuser_id);
				i.putExtra("FBuser_name", FBuser_name);
				i.putExtra("FBuser_email", FBuser_email);
				i.putExtra("FBuser_gender", FBuser_gender);

				startActivity(i);
				finish();
			}

			if (Success == true) {

				JsonFileUtility
						.CreateAndSaveFile(Constants.TAG_UserGUID, Token);
				JsonFileUtility.CreateAndSaveFile(Constants.TAG_UserObject,
						DB_USER);
				Intent i = new Intent(Login.this, Dashboard.class);

				startActivity(i);

			}

			super.onPostExecute(result);
		}
	}

	private class CheckGPlusUserTask extends AsyncTask<Void, Void, Void> {
		String jsonStr = ""; 
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			logo.startAnimation(AnimationUtils.loadAnimation(Login.this,
					R.anim.progress_animation));
			loading.setVisibility(View.VISIBLE);
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> params_fb = new ArrayList<NameValuePair>();
			params_fb.add(new BasicNameValuePair("google_id", GPlus_id));
			params_fb.add(new BasicNameValuePair("pass",
					Constants.Password_GPLUS));
			// Making a request to url and getting response
			 jsonStr = sh.makeServiceCall(url_gplus, ServiceHandler.POST,
					params_fb);

			Log.d("Response: ", "> " + jsonStr);

			if (jsonStr != null) {
				try {

					JSONObject jsonObj = new JSONObject(jsonStr);

					Success = jsonObj.getBoolean("success");
					Message = jsonObj.getString("message");

					if (Success == true) {
						Token = jsonObj.getString("token");
						JSONObject user = jsonObj.getJSONObject("user");
						DB_USER = user.toString();

					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			user_input.setEnabled(true);
			password_input.setEnabled(true);
			logo.clearAnimation();
			loading.setVisibility(View.INVISIBLE);
			if (Success == false && !GPlus_id.isEmpty() && jsonStr != null) {
				Intent i = new Intent(Login.this, SignUp.class);
				i.putExtra("GPLUS_USER_exists", true);
				i.putExtra("GPlus_id", GPlus_id);
				i.putExtra("GPlus_name", GPlus_name);
				i.putExtra("GPlus_email", GPlus_email);
				i.putExtra("GPlus_gender", GPlus_gender);

				startActivity(i);
				finish();
			}

			if (Success == true) {

				JsonFileUtility
						.CreateAndSaveFile(Constants.TAG_UserGUID, Token);
				JsonFileUtility.CreateAndSaveFile(Constants.TAG_UserObject,
						DB_USER);
				Intent i = new Intent(Login.this, Dashboard.class);
				i.putExtra("FromGoogle", true);
				startActivity(i);

			}

			super.onPostExecute(result);
		}
	}
	private boolean internetconnected() {
		
	    boolean haveConnectedWifi = false;
	    boolean haveConnectedMobile = false;

	    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
	    for (NetworkInfo ni : netInfo) {
	        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
	            if (ni.isConnected())
	                haveConnectedWifi = true;
	        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
	            if (ni.isConnected())
	                haveConnectedMobile = true;
	    }
	    return haveConnectedWifi || haveConnectedMobile;
	}
	
	@Override
	public void onConnectionFailed(ConnectionResult result) {
		if (!result.hasResolution()) {
			GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
					0).show();
			return;
		}

		if (!mIntentInProgress) {
			// Store the ConnectionResult for later usage
			mConnectionResult = result;

			if (mSignInClicked) {
				// The user has already clicked 'sign-in' so we attempt to
				// resolve all
				// errors until the user is signed in, or they cancel.
				resolveSignInError();
			}
		}
		
	}
	private void resolveSignInError() {
		if (mConnectionResult.hasResolution()) {
			try {
				mIntentInProgress = true;
				mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
			} catch (SendIntentException e) {
				mIntentInProgress = false;
				mGoogleApiClient.connect();
			}
		}
	}
	@Override
	public void onConnected(Bundle connectionHint) {
		mSignInClicked = false;
		Person Currentperson = Plus.PeopleApi
				.getCurrentPerson(mGoogleApiClient);
		GPlus_id = Currentperson.getId();
		GPlus_name = Currentperson.getDisplayName();
		GPlus_email = Plus.AccountApi.getAccountName(mGoogleApiClient);
		GPlus_gender = Currentperson.getGender();
	new CheckGPlusUserTask().execute();
		//Toast.makeText(getApplicationContext(), GPlus_id, Toast.LENGTH_SHORT).show();
			
	}

	@Override
	public void onConnectionSuspended(int cause) {
		mGoogleApiClient.connect();

	}

	public ConnectionResult getmConnectionResult() {
		return mConnectionResult;
	}

	public void setmConnectionResult(ConnectionResult mConnectionResult) {
		this.mConnectionResult = mConnectionResult;
	}
	
	@Override
	public void onBackPressed() {
		
	}
}
